<template>
  <AppLayout title="修改密码" :show-back="true">
    <view class="change-password-container">
      <!-- 安全提示 -->
      <view class="security-notice">
        <view class="notice-icon">🔐</view>
        <view class="notice-content">
          <text class="notice-title">为了您的账户安全</text>
          <text class="notice-desc">请设置一个强密码，包含字母和数字，至少6位</text>
        </view>
      </view>

      <!-- 密码修改表单 -->
      <view class="form-section">
        <view class="form-group">
          <text class="form-label">当前密码 <text class="required">*</text></text>
          <view class="input-wrapper">
            <text class="input-prefix">🔒</text>
            <input
              :value="formData.currentPassword"
              type="password"
              placeholder="请输入当前密码"
              class="form-input"
              :disabled="loading"
              :password="true"
              secure-text-entry
              @input="onCurrentPasswordInput"
              @blur="validateCurrentPassword"
            />
          </view>
          <text v-if="errors.currentPassword" class="form-error">{{ errors.currentPassword }}</text>
        </view>

        <view class="form-group">
          <text class="form-label">新密码 <text class="required">*</text></text>
          <view class="input-wrapper">
            <text class="input-prefix">🔑</text>
            <input
              :value="formData.newPassword"
              type="password"
              placeholder="请输入新密码"
              class="form-input"
              :disabled="loading"
              :password="true"
              secure-text-entry
              @input="onNewPasswordInput"
              @blur="validateNewPassword"
            />
          </view>
          <text v-if="errors.newPassword" class="form-error">{{ errors.newPassword }}</text>
        </view>

        <!-- 密码强度指示器 -->
        <view class="password-strength" v-if="formData.newPassword">
          <text class="strength-label">密码强度</text>
          <view class="strength-bar">
            <view
              class="strength-item"
              :class="getStrengthClass(1)"
            ></view>
            <view
              class="strength-item"
              :class="getStrengthClass(2)"
            ></view>
            <view
              class="strength-item"
              :class="getStrengthClass(3)"
            ></view>
            <view
              class="strength-item"
              :class="getStrengthClass(4)"
            ></view>
          </view>
          <text class="strength-text">{{ strengthText }}</text>
        </view>

        <view class="form-group">
          <text class="form-label">确认新密码 <text class="required">*</text></text>
          <view class="input-wrapper">
            <text class="input-prefix">🔑</text>
            <input
              :value="formData.confirmPassword"
              type="password"
              placeholder="请再次输入新密码"
              class="form-input"
              :disabled="loading"
              :password="true"
              secure-text-entry
              @input="onConfirmPasswordInput"
              @blur="validateConfirmPassword"
            />
          </view>
          <text v-if="errors.confirmPassword" class="form-error">{{ errors.confirmPassword }}</text>
        </view>

        <!-- 密码要求 -->
        <view class="password-requirements">
          <text class="requirements-title">密码要求：</text>
          <view class="requirement-item" :class="{ 'requirement-met': meetsLength }">
            <text class="requirement-icon">{{ meetsLength ? '✓' : '○' }}</text>
            <text class="requirement-text">至少6个字符</text>
          </view>
          <view class="requirement-item" :class="{ 'requirement-met': hasLetter }">
            <text class="requirement-icon">{{ hasLetter ? '✓' : '○' }}</text>
            <text class="requirement-text">包含字母</text>
          </view>
          <view class="requirement-item" :class="{ 'requirement-met': hasNumber }">
            <text class="requirement-icon">{{ hasNumber ? '✓' : '○' }}</text>
            <text class="requirement-text">包含数字</text>
          </view>
          <view class="requirement-item" :class="{ 'requirement-met': hasSpecial }">
            <text class="requirement-icon">{{ hasSpecial ? '✓' : '○' }}</text>
            <text class="requirement-text">包含特殊字符（可选）</text>
          </view>
        </view>
      </view>

      <!-- 操作按钮 -->
      <view class="action-section">
        <FormButton
          text="确认修改"
          type="primary"
          size="large"
          :loading="loading"
          :disabled="!canSubmit"
          block
          @click="handleChangePassword"
        />
      </view>

      <!-- 全屏加载 -->
      <AppLoading
        v-if="globalLoading"
        type="fullscreen"
        text="修改密码中..."
      />
    </view>
  </AppLayout>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { authActions, authGetters } from '@/store/modules/auth'
import { navigation } from '@/utils/navigation'
import AppLayout from '@/components/common/AppLayout.vue'
import FormButton from '@/components/common/FormButton.vue'
import AppLoading from '@/components/common/AppLoading.vue'

// 响应式数据
const loading = ref(false)
const globalLoading = ref(false)

// 表单数据
const formData = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证错误
const errors = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 计算属性
const passwordStrength = computed(() => {
  const password = formData.newPassword
  let strength = 0

  if (password.length >= 6) strength++
  if (password.length >= 8) strength++
  if (/[a-z]/.test(password) && /[A-Z]/.test(password)) strength++
  if (/\d/.test(password)) strength++
  if (/[^a-zA-Z0-9]/.test(password)) strength++

  return strength
})

const strengthText = computed(() => {
  const strength = passwordStrength.value
  if (strength === 0) return '很弱'
  if (strength === 1) return '弱'
  if (strength === 2) return '一般'
  if (strength === 3) return '强'
  if (strength === 4) return '很强'
  return '很弱'
})

const meetsLength = computed(() => formData.newPassword.length >= 6)
const hasLetter = computed(() => /[a-zA-Z]/.test(formData.newPassword))
const hasNumber = computed(() => /\d/.test(formData.newPassword))
const hasSpecial = computed(() => /[^a-zA-Z0-9]/.test(formData.newPassword))

const canSubmit = computed(() => {
  return formData.currentPassword.trim() !== '' &&
         formData.newPassword.trim() !== '' &&
         formData.confirmPassword.trim() !== '' &&
         formData.newPassword === formData.confirmPassword &&
         meetsLength.value &&
         hasLetter.value &&
         hasNumber.value &&
         Object.values(errors).every(error => error === '')
})

// 方法
/**
 * 获取强度条样式类
 */
const getStrengthClass = (level: number) => {
  const strength = passwordStrength.value
  if (strength >= level) {
    const classes = ['weak', 'fair', 'good', 'strong']
    return `strength-${classes[level - 1]}`
  }
  return ''
}

/**
 * 验证新密码
 */
const validateNewPassword = () => {
  errors.newPassword = ''

  if (!formData.newPassword.trim()) {
    errors.newPassword = '请输入新密码'
  } else if (formData.newPassword.length < 6) {
    errors.newPassword = '密码至少6个字符'
  } else if (!hasLetter.value || !hasNumber.value) {
    errors.newPassword = '密码必须包含字母和数字'
  }
}

/**
 * 验证确认密码
 */
const validateConfirmPassword = () => {
  errors.confirmPassword = ''

  if (!formData.confirmPassword.trim()) {
    errors.confirmPassword = '请确认新密码'
  } else if (formData.newPassword !== formData.confirmPassword) {
    errors.confirmPassword = '两次输入的密码不一致'
  }
}

/**
 * 处理当前密码输入
 */
const onCurrentPasswordInput = (e: any) => {
  formData.currentPassword = e.detail.value
  clearErrors()
}

/**
 * 处理新密码输入
 */
const onNewPasswordInput = (e: any) => {
  formData.newPassword = e.detail.value
  clearErrors()
}

/**
 * 处理确认密码输入
 */
const onConfirmPasswordInput = (e: any) => {
  formData.confirmPassword = e.detail.value
  clearErrors()
}

/**
 * 验证当前密码
 */
const validateCurrentPassword = () => {
  errors.currentPassword = ''
  if (!formData.currentPassword.trim()) {
    errors.currentPassword = '请输入当前密码'
  }
}

/**
 * 清除错误信息
 */
const clearErrors = () => {
  errors.currentPassword = ''
  errors.newPassword = ''
  errors.confirmPassword = ''
}

/**
 * 验证整个表单
 */
const validateForm = (): boolean => {
  clearErrors()

  let isValid = true

  // 验证当前密码
  if (!formData.currentPassword.trim()) {
    errors.currentPassword = '请输入当前密码'
    isValid = false
  }

  // 验证新密码
  validateNewPassword()
  if (errors.newPassword) isValid = false

  // 验证确认密码
  validateConfirmPassword()
  if (errors.confirmPassword) isValid = false

  return isValid
}

/**
 * 处理密码修改
 */
const handleChangePassword = async () => {
  if (!validateForm()) return

  try {
    loading.value = true
    globalLoading.value = true

    // 模拟密码修改API调用
    await new Promise(resolve => setTimeout(resolve, 1500))

    // 显示成功提示
    uni.showToast({
      title: '密码修改成功',
      icon: 'success',
      duration: 2000
    })

    // 清空表单
    formData.currentPassword = ''
    formData.newPassword = ''
    formData.confirmPassword = ''
    clearErrors()

    // 延迟跳转
    setTimeout(() => {
      navigation.toHome()
    }, 2000)

  } catch (error) {
    console.error('密码修改失败:', error)

    uni.showToast({
      title: '密码修改失败，请重试',
      icon: 'error'
    })
  } finally {
    loading.value = false
    globalLoading.value = false
  }
}
</script>

<style lang="scss" scoped>
.change-password-container {
  min-height: 100vh;
  background: #f8f9fa;
  padding: 20px;
}

.security-notice {
  display: flex;
  align-items: center;
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  border-left: 4px solid #1890ff;

  .notice-icon {
    font-size: 32px;
    margin-right: 16px;
  }

  .notice-content {
    flex: 1;

    .notice-title {
      display: block;
      font-size: 16px;
      font-weight: 600;
      color: #333;
      margin-bottom: 4px;
    }

    .notice-desc {
      display: block;
      font-size: 14px;
      color: #666;
      line-height: 1.4;
    }
  }
}

.form-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
}

.password-strength {
  margin: 16px 0;

  .strength-label {
    display: block;
    font-size: 14px;
    font-weight: 500;
    color: #666;
    margin-bottom: 8px;
  }

  .strength-bar {
    display: flex;
    gap: 4px;
    margin-bottom: 8px;

    .strength-item {
      flex: 1;
      height: 6px;
      background: #f0f0f0;
      border-radius: 3px;
      transition: all 0.3s ease;

      &.strength-weak {
        background: #ff4757;
      }

      &.strength-fair {
        background: #ffa502;
      }

      &.strength-good {
        background: #ffdd59;
      }

      &.strength-strong {
        background: #5cb85c;
      }
    }
  }

  .strength-text {
    font-size: 12px;
    color: #666;
    font-weight: 500;
  }
}

.password-requirements {
  margin-top: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;

  .requirements-title {
    display: block;
    font-size: 14px;
    font-weight: 600;
    color: #333;
    margin-bottom: 12px;
  }

  .requirement-item {
    display: flex;
    align-items: center;
    margin-bottom: 8px;

    &:last-child {
      margin-bottom: 0;
    }

    &.requirement-met {
      .requirement-icon {
        color: #5cb85c;
      }

      .requirement-text {
        color: #5cb85c;
      }
    }

    .requirement-icon {
      font-size: 16px;
      margin-right: 8px;
      color: #ddd;
      width: 16px;
      text-align: center;
    }

    .requirement-text {
      font-size: 13px;
      color: #666;
    }
  }
}

.action-section {
  padding: 0 20px;
}

// 响应式设计
@media (max-width: 480px) {
  .change-password-container {
    padding: 16px;
  }

  .form-section {
    padding: 20px 16px;
  }

  .action-section {
    padding: 0;
  }
}

/* 表单样式 */
.form-group {
  margin-bottom: 20px;
}

.form-label {
  display: block;
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
}

.required {
  color: #ff4757;
  margin-left: 2px;
}

.input-wrapper {
  display: flex;
  align-items: center;
  border: 1px solid #e1e8ed;
  border-radius: 8px;
  background: #ffffff;
  padding: 0 12px;
  transition: border-color 0.3s ease;
}

.input-wrapper:focus-within {
  border-color: #1890ff;
}

.input-prefix {
  font-size: 16px;
  color: #999;
  margin-right: 8px;
}

.form-input {
  flex: 1;
  height: 44px;
  font-size: 14px;
  color: #333;
  background: transparent;
  border: none;
  outline: none;
}

.form-input::placeholder {
  color: #999;
}

.form-error {
  display: block;
  font-size: 12px;
  color: #ff4757;
  margin-top: 4px;
}

.form-input:disabled {
  background: #f5f5f5;
  color: #999;
}

// 动画
.form-section {
  animation: slideUp 0.6s cubic-bezier(0.4, 0, 0.2, 1);
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>